#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
主菜单界面
提供游戏的主要功能入口
"""

import os
from typing import Optional
from ..game.game_manager import GameManager
from .character_ui import CharacterUI
from .idle_ui import IdleUI
from .battle_ui import BattleUI

class MainMenu:
    """
    主菜单类
    """
    
    def __init__(self, game_manager: GameManager):
        """
        初始化主菜单
        
        Args:
            game_manager: 游戏管理器
        """
        self.game_manager = game_manager
        self.character_ui = CharacterUI(game_manager)
        self.idle_ui = IdleUI(game_manager)
        self.battle_ui = BattleUI(game_manager)
        self.running = True
    
    def clear_screen(self):
        """
        清屏
        """
        os.system('cls' if os.name == 'nt' else 'clear')
    
    def show_header(self):
        """
        显示游戏标题
        """
        print("\n" + "=" * 60)
        print("                    VX BATTLE")
        print("                 微信小游戏原型")
        print("=" * 60)
        
        # 显示当前角色信息
        current_character = self.game_manager.get_current_character()
        if current_character:
            print(f"当前角色: {current_character.name} (Lv.{current_character.level} {current_character.character_class})")
            print(f"HP: {current_character.hp}/{current_character.max_hp} | MP: {current_character.mp}/{current_character.max_mp}")
            print(f"经验: {current_character.exp}/{current_character.exp_to_next_level}")
            
            # 显示状态
            if current_character.is_idle:
                idle_status = self.game_manager.get_idle_status()
                if idle_status:
                    duration = idle_status['duration']
                    hours = int(duration // 3600)
                    minutes = int((duration % 3600) // 60)
                    print(f"状态: 在 {idle_status['location_name']} 挂机中 ({hours}h {minutes}m)")
            elif current_character.is_in_battle:
                print(f"状态: 战斗中 (战斗ID: {current_character.battle_id})")
            else:
                print("状态: 空闲")
        else:
            print("当前角色: 未选择")
        
        print("=" * 60)
    
    def show_menu_options(self):
        """
        显示菜单选项
        """
        print("\n请选择操作:")
        print("1. 角色管理")
        print("2. 挂机系统")
        print("3. 战斗系统")
        print("4. 游戏统计")
        print("5. 保存游戏")
        print("0. 退出游戏")
        print("-" * 30)
    
    def show_game_stats(self):
        """
        显示游戏统计信息
        """
        self.clear_screen()
        print("\n" + "=" * 40)
        print("           游戏统计")
        print("=" * 40)
        
        stats = self.game_manager.get_game_stats()
        
        # 游戏时间
        play_time = stats['play_time']
        hours = int(play_time // 3600)
        minutes = int((play_time % 3600) // 60)
        print(f"游戏时长: {hours}小时 {minutes}分钟")
        
        # 角色统计
        char_stats = stats['character_stats']
        print(f"\n角色统计:")
        print(f"  总角色数: {char_stats['total_characters']}")
        print(f"  最高等级: {char_stats['max_level']}")
        print(f"  当前角色: {char_stats['current_character'] or '未选择'}")
        
        # 职业分布
        if char_stats['class_distribution']:
            print(f"\n职业分布:")
            for class_name, count in char_stats['class_distribution'].items():
                print(f"  {class_name}: {count}个")
        
        print("\n" + "=" * 40)
        input("\n按回车键返回主菜单...")
    
    def handle_menu_choice(self, choice: str) -> bool:
        """
        处理菜单选择
        
        Args:
            choice: 用户选择
            
        Returns:
            是否继续运行
        """
        if choice == "1":
            self.character_ui.show()
        elif choice == "2":
            self.idle_ui.show()
        elif choice == "3":
            self.battle_ui.show()
        elif choice == "4":
            self.show_game_stats()
        elif choice == "5":
            self.game_manager.save_game()
            print("\n游戏已保存!")
            input("按回车键继续...")
        elif choice == "0":
            return self.confirm_exit()
        else:
            print("\n无效选择，请重新输入!")
            input("按回车键继续...")
        
        return True
    
    def confirm_exit(self) -> bool:
        """
        确认退出
        
        Returns:
            是否继续运行（False表示退出）
        """
        print("\n确定要退出游戏吗？")
        print("1. 保存并退出")
        print("2. 直接退出")
        print("3. 取消")
        
        while True:
            choice = input("\n请选择 (1-3): ").strip()
            
            if choice == "1":
                self.game_manager.save_game()
                print("\n游戏已保存，感谢游玩!")
                return False
            elif choice == "2":
                print("\n感谢游玩!")
                return False
            elif choice == "3":
                return True
            else:
                print("无效选择，请重新输入!")
    
    def show(self):
        """
        显示主菜单
        """
        while self.running and self.game_manager.running:
            self.clear_screen()
            self.show_header()
            self.show_menu_options()
            
            try:
                choice = input("请输入选择 (0-5): ").strip()
                self.running = self.handle_menu_choice(choice)
            except KeyboardInterrupt:
                print("\n\n检测到 Ctrl+C，正在退出...")
                self.running = False
            except Exception as e:
                print(f"\n发生错误: {e}")
                input("按回车键继续...")
        
        # 游戏结束时保存数据
        self.game_manager.shutdown()